use crate::{
    common::AppError,
    model::entity::User,
    model::form::{AuthResponse, CreateUser},
    repository::user_repository,
    service::{self, auth::create_jwt},
};
use axum::{
    extract::{Extension, Json},
    response::Json as JsonResponse,
};
use sqlx::PgPool;

pub async fn create_user_handler(
    Extension(pool): Extension<PgPool>,
    Json(payload): Json<CreateUser>,
) -> Result<JsonResponse<AuthResponse>, AppError> {
    let hashed_password = service::auth::hash_password(&payload.password)?;
    let user =
        user_repository::create_user(&pool, &payload.username, &payload.email, &hashed_password)
            .await?;
    let token = create_jwt(user.id)?;

    Ok(JsonResponse(AuthResponse { token, user }))
}

pub async fn get_users_handler(
    Extension(pool): Extension<PgPool>,
) -> Result<JsonResponse<Vec<User>>, AppError> {
    let users = user_repository::get_all_users(&pool).await?;
    Ok(JsonResponse(users))
}
